package com.park.gateway.filters;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.io.IOException;

/**
 * @ClassName GateGlobalFilter
 * @Description 全局过滤器
 * @Date 2023/5/26 19:28
 * @Author huxiaohua
 */
@Component
@Slf4j
public class GateGlobalFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        try {
            logRequestInfo(exchange);
        } catch (Exception e) {
            log.error("打印请求参数异常", e);
        }
        try {
            return chain.filter(exchange);
        } catch (Exception e) {
            log.error("接口调用异常 ======> ", e);
        }
        return Mono.empty();
    }

    private void logRequestInfo(ServerWebExchange exchange) throws IOException {
        ServerHttpRequest request = exchange.getRequest();
        StringBuilder reqSb = new StringBuilder("\r\n");
        reqSb.append("      请求URI：" + request.getURI().getPath()).append("\r\n");
        reqSb.append("      请求METHOD：" + request.getMethodValue()).append("\r\n");
        reqSb.append("      请求LocalAddress：" + request.getLocalAddress()).append("\r\n");
        reqSb.append("      请求RemoteAddress：" + request.getRemoteAddress()).append("\r\n");
        reqSb.append("      请求Header：").append(request.getHeaders()).append("\r\n");
        log.info(reqSb.toString());
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }


}
